const express = require("express");
const fs = require("fs")

const app = express()

app.use(express.static("./www"))

app.get("/getGoods", (req,res,next)=>{
    fs.readFile("./data/goods.json", "utf-8", (err,data)=>{
        if(err){
            res.send(JSON.stringify({
                code:0,
                msg:"数据请求失败",
                data:null
            }))
        }else{
            res.send(JSON.stringify({
                code:1,
                msg:"数据请求成功",
                data:JSON.parse(data)
            }))
        }
    })
})

app.get("/getDetail", (req,res,next)=>{
    const id = req.query.id;
    fs.readFile("./data/goods.json", "utf-8", (err,data)=>{
        const d = JSON.parse(data);
        let i;
        const flag = d.some((val,idx)=>{
            i = idx;
            return val.id.toString() === id;
        })
        if(flag){
            res.send(JSON.stringify({
                code:1,
                msg:"获取成功",
                data:d[i]
            }));
        }else{
            res.send(JSON.stringify({
                code:0,
                msg:"没有对应商品，请检查id是否正确",
                data:null
            }));
        }
    })
})


app.listen(3000);